//
//  NetWorkTools.swift
//  Zayl--weibo
//
//  Created by 张玉 on 15/9/8.
//  Copyright © 2015年 ZY. All rights reserved.
//

import UIKit
import AFNetworking
/// 错误的类别标记 错误域 捕获错误
private let ZaylErrorDomainName = "com.baidu.error.network"
class NetWorkTools: AFHTTPSessionManager {

    //单例 因为新浪微博有Base URL
    static let sharedTools:NetWorkTools = {
        //懒加载 设置BASE url
        let baseURL = NSURL(string: "https://api.weibo.com/")!
        let tools = NetWorkTools(baseURL: baseURL)
        
        //设置数据解析类型
        tools.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript", "text/plain") as Set<NSObject>
        return tools
        
        
    }()
    //MARK:- 加载用户数据
    /// 加载用户信息 － 职责，做网络访问，获取到 dict
    func loadUserInfo(uid: String, finished:ZaylNetFinishedCallBack) {
        // 判断 token 是否存在
        if UserAccount.loadAccount()?.access_token == nil {
            return
        }
        
        let urlString = "2/users/show.json"
        let params:[String:AnyObject] = ["access_token":UserAccount.loadAccount()!.access_token!,"uid":uid]
        // 发送网络请求
        // 提示：如果参数不正确，首先用 option + click 确认参数类型
        requestGET(urlString, pargrams: params, finished: finished)
        
    }
    
    //MARK: - OAuth授权
    private let clientId = "1167204004"
    private let  appSecret = "bf687c2f8869e10a02a6ee3ea96bd091"
    //回掉地址
    let redirectUri = "http://user.qzone.qq.com/915859382/infocenter"
    //定义函数返回URL
    func oauthURL()->NSURL {
        //定义url 拼接网络请求的路劲
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(clientId)&redirect_uri=\(redirectUri)"
        //url是可选的需要加!解包 自己拼接的 能保证绝对有值
        return NSURL(string: urlString)!
        
    }
    /// 使用 code 获取 accessToken
    ///
    /// - parameter code: 请求码 回掉token和错误
    func loadAccessToken (code:String,finished:(result:[String:AnyObject]?,error:NSError?)->()) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id":clientId,
            "client_secret":appSecret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":redirectUri]
        //post上传
        POST(urlString, parameters: params, success: { (_, JSON) -> Void in
            finished(result: JSON as? [String:AnyObject], error: nil)
            }) { (_, error ) -> Void in
                finished(result: nil, error: error)
        }
    }
    //MARK:- 封装 AFN 网络方法，便于替换网络访问方法，第三方框架的网络代码全部集中在此
    /// 网络回调类型别名
    typealias ZaylNetFinishedCallBack = (result:[String:AnyObject]?,error:NSError?)->()
    /// GET 请求
    ///
    /// :param: urlString URL 地址
    /// :param: params    参数字典
    /// :param: finished  完成回调
    
    private func requestGET(urlString:String,pargrams:[String: AnyObject],finished:ZaylNetFinishedCallBack) {
        
        GET(urlString, parameters: pargrams, success: { (_, JSON) -> Void in
            if let result = JSON as? [String:AnyObject]{
             // 有结果的回调
            finished(result: result, error: nil)
            }else {
                // 没有错误，同时没有结果
                print("没有数据 GET Request \(urlString)")
                /**
                domain: 错误的范围/大类别，定义一个常量字符串
                code: 错误代号，有些公司会专门定义一个特别大的.h，定义所有的错误编码，通常是负数
                userInfo: 可以传递一些附加的错误信息
                */
                let error  = NSError(domain: ZaylErrorDomainName, code: -1, userInfo: ["errorMessage" : "空数据"])
                finished(result: nil, error: error)
                

            }
            }) { (_, error) -> Void in
                print(error)
                finished(result: nil, error: error)
                
        }
    }
    
}
